package com.clz.latte.net.download;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;

import com.clz.latte.app.Latte;
import com.clz.latte.net.callback.IRequest;
import com.clz.latte.net.callback.ISuccess;
import com.clz.latte.utils.file.FileUtil;

import java.io.File;
import java.io.InputStream;

import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2017/12/5.
 */

public class SavaFileTask extends AsyncTask<Object, Void, File> {
    private final ISuccess Sucess;
    private final IRequest REQUEST;

    public SavaFileTask(ISuccess sucess, IRequest REQUEST) {
        Sucess = sucess;
        this.REQUEST = REQUEST;
    }

    @Override
    protected File doInBackground(Object... objects) {
        String downloadDir = (String) objects[0];
        String extension = (String) objects[1];
        ResponseBody responseBody = (ResponseBody) objects[2];
        final InputStream is = responseBody.byteStream();
        String fileName = (String) objects[3];
        if (downloadDir == null || downloadDir.equals("")) {
            downloadDir = "downloads";
        }
        if (extension == null || extension.equals("")) {
            extension = "";
        }
        if (fileName == null) {
            return FileUtil.writeToDisk(is, downloadDir, extension.toUpperCase(), extension);
        } else {
            return FileUtil.writeToDisk(is, downloadDir, fileName);
        }
    }

    @Override
    protected void onPostExecute(File file) {
        super.onPostExecute(file);
        if (Sucess != null) {
            Sucess.onSucess(file.getPath());
        }
        if (REQUEST != null) {
            REQUEST.onRequestEnd();
        }
        autoInstallApk(file);
    }

    private void autoInstallApk(File file) {
        if (FileUtil.getExtension(file.getPath()).equals("apk")) {
            Intent insatll = new Intent();
            insatll.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            insatll.setAction(Intent.ACTION_VIEW);
            insatll.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            Latte.getAppplication().startActivity(insatll);
        }
    }

}
